package main

import (
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"os"
)

var tp string = "md5"

func Md5String(data string) string {
	md5 := md5.New()
	md5.Write([]byte(data))
	md5Data := md5.Sum([]byte(nil))
	return hex.EncodeToString(md5Data)
}

func Md5(data []byte) string {
	md5 := md5.New()
	md5.Write(data)
	md5Data := md5.Sum([]byte(nil))
	return hex.EncodeToString(md5Data)
}

func HmacString(key string, data string) string {
	hmac := hmac.New(md5.New, []byte(key))
	hmac.Write([]byte(data))
	return hex.EncodeToString(hmac.Sum([]byte(nil)))
}

func HmacByStringKey(key string, data []byte) string {
	return Hmac([]byte(key), data)
}

func Hmac(key []byte, data []byte) string {
	hmac := hmac.New(md5.New, key)
	hmac.Write(data)
	return hex.EncodeToString(hmac.Sum([]byte(nil)))
}

func Sha1String(data string) string {
	sha1 := sha1.New()
	sha1.Write([]byte(data))
	return hex.EncodeToString(sha1.Sum([]byte(nil)))
}

func Sha1(data []byte) string {
	sha1 := sha1.New()
	sha1.Write(data)
	return hex.EncodeToString(sha1.Sum([]byte(nil)))
}

//上面的代码都是抄的
func main() {
	if len(os.Args) == 1 {
		tip := `
			Usage: md5.exe  md5/sha1  filename  filename ...
		`
		fmt.Println(tip)
		os.Exit(1)
	}

	var files []string
	if len(os.Args) == 2 {
		files = os.Args[1:]
	} else {
		tp = os.Args[1]
		files = os.Args[2:]
	}
	for _, fn := range files {
		t := handleFile(fn)
		fmt.Println(t)
	}

}

func handleFile(fileName string) (result string) {
	file, err := os.Open(fileName)
	checkError(err)
	content, err := ioutil.ReadAll(file)
	checkError(err)
	switch tp {
	case "md5":
		result = Md5(content)
	case "sha1":
		result = Sha1(content)
	}
	return
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error:%s", err.Error())
		os.Exit(1)
	}
}
